package org.example.service;

import org.example.mapper.DataSourceConfigMapper;
import org.example.model.DataSourceConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author by PengHongChao
 * @date 2025/7/7 10:31
 */
@Service
public class DataSourceConfigService {
    private final DataSourceConfigMapper configMapper;
    private final DataSourceManager dataSourceManager;

    public DataSourceConfigService(DataSourceConfigMapper configMapper,
                                   DataSourceManager dataSourceManager) {
        this.configMapper = configMapper;
        this.dataSourceManager = dataSourceManager;
    }

    @Transactional
    public void createDataSource(DataSourceConfig config) {
        configMapper.insert(config);
        dataSourceManager.registerDataSource(config);
    }

    @Transactional
    public void updateDataSource(DataSourceConfig config) {
        configMapper.update(config);
        dataSourceManager.unregisterDataSource(config.getId());
        dataSourceManager.registerDataSource(config);
    }

    @Transactional
    public void deleteDataSource(Long id) {
        configMapper.delete(id);
        dataSourceManager.unregisterDataSource(id);
    }

    public List<DataSourceConfig> listAll() {
        return configMapper.selectAll();
    }

    public DataSourceConfig getById(Long id) {
        return configMapper.selectById(id);
    }

    public boolean testConnection(DataSourceConfig config) {
        // 实际实现需调用具体DataSourceProvider的testConnection
        // 简化版直接尝试获取连接
        try {
            dataSourceManager.getJdbcTemplate(config.getId()).execute("SELECT 1");
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
